/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Logs;
import entities.RopaBlanca;
import entities.UnidadesAlojamiento;
import entities.Usuarios;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.ExcelJTableExporter;

/**
 *
 * @author Smuggler
 */
public class AltaUnidadAlojamiento extends JPanel {

    private Logs logs;
    public static JFrame frame;
    private Usuarios usuario;
    private UnidadesAlojamiento u;

    public AltaUnidadAlojamiento(Usuarios usuario) {
        initComponents();
        limpiarcampos();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.usuario = usuario;
    }

    public JFrame getFrame() {
        return frame;
    }

    private Integer getIDUnidadAlojamiento(String nombre) {
        Query queryIDUnidadAlojamiento;
        UnidadesAlojamiento ua;
        queryIDUnidadAlojamiento = entityManager.createNamedQuery("UnidadesAlojamiento.findByNombre");
        queryIDUnidadAlojamiento.setParameter("nombre", nombre);
        ua = (UnidadesAlojamiento) queryIDUnidadAlojamiento.getSingleResult();
        return ua.getIdUnidad();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u ORDER BY u.nombre ASC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        nombreLabel = new javax.swing.JLabel();
        ubicaciónLabel = new javax.swing.JLabel();
        capacidadLabel = new javax.swing.JLabel();
        categoriaLabel = new javax.swing.JLabel();
        ambientesLabel = new javax.swing.JLabel();
        dormitoriosLabel = new javax.swing.JLabel();
        patioLabel = new javax.swing.JLabel();
        parrillaLabel = new javax.swing.JLabel();
        cocheraLabel = new javax.swing.JLabel();
        observacionLabel = new javax.swing.JLabel();
        nombreField = new javax.swing.JTextField();
        guardarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        patioComboBox = new javax.swing.JComboBox();
        parrilaComboBox = new javax.swing.JComboBox();
        cocheraComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        observacionTextArea = new javax.swing.JTextArea();
        dormitorioSpinner = new javax.swing.JSpinner();
        ambienteSpinner = new javax.swing.JSpinner();
        categoriaComboBox = new javax.swing.JComboBox();
        capacidadSpinner = new javax.swing.JSpinner();
        ubicacionComboBox = new javax.swing.JComboBox();
        cancelarButton = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        ayudaLabel = new javax.swing.JLabel();
        activoComboBox = new javax.swing.JComboBox();
        activoLabel = new javax.swing.JLabel();
        exportarExcelButton = new javax.swing.JButton();

        FormListener formListener = new FormListener();

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nombre}"));
        columnBinding.setColumnName("Nombre");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${ubicación}"));
        columnBinding.setColumnName("Ubicación");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${capacidad}"));
        columnBinding.setColumnName("Capacidad");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${categoria}"));
        columnBinding.setColumnName("Categoria");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${ambientes}"));
        columnBinding.setColumnName("Ambientes");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${dormitorios}"));
        columnBinding.setColumnName("Dormitorios");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${patio}"));
        columnBinding.setColumnName("Patio");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${parrilla}"));
        columnBinding.setColumnName("Parrilla");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cochera}"));
        columnBinding.setColumnName("Cochera");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${observacion}"));
        columnBinding.setColumnName("Observacion");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${activo}"));
        columnBinding.setColumnName("Activo");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(1).setResizable(false);
        masterTable.getColumnModel().getColumn(2).setResizable(false);
        masterTable.getColumnModel().getColumn(3).setResizable(false);
        masterTable.getColumnModel().getColumn(4).setResizable(false);
        masterTable.getColumnModel().getColumn(5).setResizable(false);
        masterTable.getColumnModel().getColumn(6).setResizable(false);
        masterTable.getColumnModel().getColumn(7).setResizable(false);
        masterTable.getColumnModel().getColumn(8).setResizable(false);
        masterTable.getColumnModel().getColumn(9).setResizable(false);
        masterTable.getColumnModel().getColumn(10).setResizable(false);

        nombreLabel.setText("Nombre:");

        ubicaciónLabel.setText("Ubicación:");

        capacidadLabel.setText("Capacidad:");

        categoriaLabel.setText("Categoria:");

        ambientesLabel.setText("Ambientes:");

        dormitoriosLabel.setText("Dormitorios:");

        patioLabel.setText("Patio:");

        parrillaLabel.setText("Parrilla:");

        cocheraLabel.setText("Cochera:");

        observacionLabel.setText("Observaciones:");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.nombre}"), nombreField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), nombreField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        nombreField.addKeyListener(formListener);

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), guardarButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        guardarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(formListener);

        patioComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NO", "SI" }));
        patioComboBox.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.patio}"), patioComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        parrilaComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NO", "SI" }));
        parrilaComboBox.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.parrilla}"), parrilaComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cocheraComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NO", "SI" }));
        cocheraComboBox.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cochera}"), cocheraComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        observacionTextArea.setColumns(20);
        observacionTextArea.setRows(5);
        observacionTextArea.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.observacion}"), observacionTextArea, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jScrollPane1.setViewportView(observacionTextArea);

        dormitorioSpinner.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.dormitorios}"), dormitorioSpinner, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        ambienteSpinner.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.ambientes}"), ambienteSpinner, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        categoriaComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SUPERIOR", "PREMIUM" }));
        categoriaComboBox.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.categoria}"), categoriaComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        capacidadSpinner.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.capacidad}"), capacidadSpinner, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        ubicacionComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "PB", "1P" }));
        ubicacionComboBox.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.ubicación}"), ubicacionComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");
        cancelarButton.setEnabled(false);
        cancelarButton.addActionListener(formListener);

        ayudaLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel.addMouseListener(formListener);

        activoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SI", "NO" }));
        activoComboBox.setEnabled(false);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.activo}"), activoComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        activoLabel.setText("Activo:");

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(ambientesLabel)
                                    .addComponent(dormitoriosLabel))
                                .addGap(10, 10, 10)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(ambienteSpinner)
                                    .addComponent(dormitorioSpinner)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cocheraLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(parrillaLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(parrilaComboBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cocheraComboBox, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(patioLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(patioComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(observacionLabel)
                                .addGap(39, 39, 39)
                                .addComponent(activoLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(activoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jScrollPane1)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(ayudaLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exportarExcelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(nuevoButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(guardarButton))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(nombreLabel)
                        .addGap(11, 11, 11)
                        .addComponent(nombreField, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(ubicaciónLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(ubicacionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(categoriaLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(categoriaComboBox, 0, 407, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(capacidadLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(capacidadSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addContainerGap())
            .addComponent(jSeparator1)
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {guardarButton, nuevoButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombreLabel)
                    .addComponent(nombreField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ubicaciónLabel)
                    .addComponent(ubicacionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(capacidadLabel)
                    .addComponent(capacidadSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(ambientesLabel)
                        .addComponent(ambienteSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(categoriaLabel)
                            .addComponent(categoriaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(observacionLabel)
                            .addComponent(activoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(activoLabel))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(dormitorioSpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(dormitoriosLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(patioLabel)
                            .addComponent(patioComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(parrillaLabel)
                            .addComponent(parrilaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(8, 8, 8)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cocheraComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cocheraLabel)))
                    .addComponent(jScrollPane1))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(guardarButton)
                            .addComponent(nuevoButton)
                            .addComponent(cancelarButton)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(ayudaLabel))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(exportarExcelButton)))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.KeyListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                AltaUnidadAlojamiento.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                AltaUnidadAlojamiento.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                AltaUnidadAlojamiento.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                AltaUnidadAlojamiento.this.exportarExcelButtonActionPerformed(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == nombreField) {
                AltaUnidadAlojamiento.this.nombreFieldKeyReleased(evt);
            }
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                AltaUnidadAlojamiento.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel) {
                AltaUnidadAlojamiento.this.ayudaLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    private void habilitarBotones(boolean estado) {
        nuevoButton.setEnabled(!estado);
        masterTable.setEnabled(!estado);

        cancelarButton.setEnabled(estado);
        nombreField.setEnabled(estado);
        ubicacionComboBox.setEnabled(estado);
        capacidadSpinner.setEnabled(estado);
        categoriaComboBox.setEnabled(estado);
        ambienteSpinner.setEnabled(estado);
        dormitorioSpinner.setEnabled(estado);
        patioComboBox.setEnabled(estado);
        parrilaComboBox.setEnabled(estado);
        cocheraComboBox.setEnabled(estado);
        observacionTextArea.setEnabled(estado);
        activoComboBox.setEnabled(estado);
    }

    private void setearCampos() {
        ubicacionComboBox.setSelectedIndex(0);
        categoriaComboBox.setSelectedIndex(0);
        patioComboBox.setSelectedIndex(0);
        parrilaComboBox.setSelectedIndex(0);
        cocheraComboBox.setSelectedIndex(0);
        activoComboBox.setSelectedIndex(0);
//    capacidadSpinner.setValue(1);
//    ambienteSpinner.setValue(1);
//    dormitorioSpinner.setValue(1);
    }

    private void limpiarcampos() {
        nombreField.setText("");
        ubicacionComboBox.setSelectedIndex(-1);
        categoriaComboBox.setSelectedIndex(-1);
        patioComboBox.setSelectedIndex(-1);
        parrilaComboBox.setSelectedIndex(-1);
        cocheraComboBox.setSelectedIndex(-1);
        capacidadSpinner.setValue(1);
        ambienteSpinner.setValue(1);
        dormitorioSpinner.setValue(1);
        observacionTextArea.setText("");
        activoComboBox.setSelectedIndex(-1);
    }

    private void refrescar() {
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        habilitarBotones(false);
        limpiarcampos();
    }
    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        u = new entities.UnidadesAlojamiento();
        logs = new Logs();
        logs.setUsuario(usuario);
        entityManager.persist(u);
        list.add(u);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
        habilitarBotones(true);
        setearCampos();
        
    }//GEN-LAST:event_nuevoButtonActionPerformed

    /*
     * private boolean existeNombre(String localizador) { int row =
     * masterTable.getSelectedRow(); int contador = 0; for (UnidadesAlojamiento
     * unidad : list.subList(0, list.size() - 1)) { if (row != contador) { if
     * (unidad.getNombre() == null ? localizador == null :
     * unidad.getNombre().equals(localizador)) { return true; } } contador++; }
     * return false; }
     */
    private boolean existeNombre(String nombre) {
        int cont = 0;
        for (UnidadesAlojamiento unidadesAlojamiento : list) {
            if (unidadesAlojamiento.getNombre().equalsIgnoreCase(nombre)) {
                cont++;
            }
        }
        if (cont < 2) {
            return false;
        }
        return true;
    }

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        if ("".equals(nombreField.getText())) {
            JOptionPane.showMessageDialog(this, "Complete el Nombre", "Atención", WIDTH, null);
            nombreField.requestFocus();
        } else if (existeNombre(nombreField.getText())) {
            JOptionPane.showMessageDialog(this, "Ya existe el Nombre", "Atención", WIDTH, null);
            nombreField.requestFocus();
        } else {
            try {
                logs = new Logs();
                logs.setUsuario(usuario);
                if (u.getIdUnidad() == null) {
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                    Integer idUnidadAlojamiento = getIDUnidadAlojamiento(u.getNombre());
                    logs.setearObservaciones("Alta", "UnidadesAlojamiento", idUnidadAlojamiento, "AltaUnidadAlojamiento");
                } else {
                    logs.setearObservaciones("Modificación", "UnidadesAlojamiento", u.getIdUnidad(), "AltaUnidadAlojamiento");
                }
                entityManager.persist(logs);
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();
            } catch (RollbackException rex) {
                rex.printStackTrace();
                entityManager.getTransaction().begin();
                List<entities.UnidadesAlojamiento> merged = new ArrayList<entities.UnidadesAlojamiento>(list.size());
                for (entities.UnidadesAlojamiento u : list) {
                    merged.add(entityManager.merge(u));
                }
                list.clear();
                list.addAll(merged);
            }
            habilitarBotones(false);
            refrescar();
        }
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        refrescar(); // TODO add your handling code here:
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        habilitarBotones(true);
        u = list.get(masterTable.getSelectedRow());
    }//GEN-LAST:event_masterTableMouseClicked

    private void nombreFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombreFieldKeyReleased
        String texto = nombreField.getText().toUpperCase();
        nombreField.setText(texto);
    }//GEN-LAST:event_nombreFieldKeyReleased

    private void ayudaLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabelMouseEntered
        ayudaLabel.setToolTipText("En esta pantalla usted podra agregar,\n editar y eliminar unidades de alojamiento");
    }//GEN-LAST:event_ayudaLabelMouseEntered

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        new ExcelJTableExporter(masterTable, "Unidades de Alojamiento").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox activoComboBox;
    private javax.swing.JLabel activoLabel;
    private javax.swing.JSpinner ambienteSpinner;
    private javax.swing.JLabel ambientesLabel;
    private javax.swing.JLabel ayudaLabel;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JLabel capacidadLabel;
    private javax.swing.JSpinner capacidadSpinner;
    private javax.swing.JComboBox categoriaComboBox;
    private javax.swing.JLabel categoriaLabel;
    private javax.swing.JComboBox cocheraComboBox;
    private javax.swing.JLabel cocheraLabel;
    private javax.swing.JSpinner dormitorioSpinner;
    private javax.swing.JLabel dormitoriosLabel;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private javax.swing.JButton guardarButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private java.util.List<entities.UnidadesAlojamiento> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JTextField nombreField;
    private javax.swing.JLabel nombreLabel;
    private javax.swing.JButton nuevoButton;
    private javax.swing.JLabel observacionLabel;
    private javax.swing.JTextArea observacionTextArea;
    private javax.swing.JComboBox parrilaComboBox;
    private javax.swing.JLabel parrillaLabel;
    private javax.swing.JComboBox patioComboBox;
    private javax.swing.JLabel patioLabel;
    private javax.persistence.Query query;
    private javax.swing.JComboBox ubicacionComboBox;
    private javax.swing.JLabel ubicaciónLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AltaUnidadAlojamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AltaUnidadAlojamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AltaUnidadAlojamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AltaUnidadAlojamiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        final Usuarios usuario = user;
        /*
         * Create and display the form
         */
        AltaUnidadAlojamiento.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setTitle("Inventario - Unidades de alojamiento");
                frame.setContentPane(new AltaUnidadAlojamiento(usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Inventario   -   Unidades de Alojamiento   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
